
import os
import sys
import time
import logging
from datetime import datetime
from typing import Optional, Any

# 配置日志
logger = logging.getLogger(__name__)

def safe_import_module(module_name: str, class_name: str, alias: str = None) -> Optional[Any]:
    """安全导入模块，返回类或None"""
    try:
        module = __import__(module_name, fromlist=[class_name])
        cls = getattr(module, class_name)
        display_name = alias or class_name
        logger.info(f"✅ {display_name} 导入成功")
        return cls
    except ImportError as e:
        logger.warning(f"⚠️ {alias or class_name} 导入失败: {e}")
        return None
    except Exception as e:
        logger.error(f"❌ {alias or class_name} 导入异常: {e}")
        return None

def get_system_performance():
    """获取系统性能指标"""
    try:
        import psutil

        cpu_percent = psutil.cpu_percent(interval=1)
        memory = psutil.virtual_memory()
        memory_used = memory.used / (1024 * 1024)
        memory_total = memory.total / (1024 * 1024)
        memory_percent = memory.percent
        disk = psutil.disk_usage('.')
        disk_free = disk.free / (1024 * 1024 * 1024)
        boot_time = psutil.boot_time()
        uptime_seconds = time.time() - boot_time
        uptime_hours = uptime_seconds / 3600
        uptime = f"{uptime_hours:.1f}小时" if uptime_hours < 24 else f"{uptime_hours / 24:.1f}天"

        return {
            'cpu_percent': cpu_percent,
            'memory_used': memory_used,
            'memory_total': memory_total,
            'memory_percent': memory_percent,
            'disk_free': disk_free,
            'uptime': uptime
        }
    except ImportError:
        return {
            'cpu_percent': 0.0, 'memory_used': 0.0, 'memory_total': 0.0,
            'memory_percent': 0.0, 'disk_free': 0.0, 'uptime': '未知'
        }
    except Exception as e:
        logger.error(f"获取系统性能指标失败: {e}")
        return {
            'cpu_percent': 0.0, 'memory_used': 0.0, 'memory_total': 0.0,
            'memory_percent': 0.0, 'disk_free': 0.0, 'uptime': '获取失败'
        }

def get_health_status_icon(health_score):
    """根据健康度分数获取状态图标"""
    if health_score >= 90: return "🟢"
    if health_score >= 70: return "🟡"
    if health_score >= 50: return "🟠"
    return "🔴"

def check_pytdx_connection():
    """检查pytdx连接"""
    try:
        from pytdx.hq import TdxHq_API
        api = TdxHq_API()
        servers = [('221.131.136.194', 7709), ('111.229.200.45', 7709), ('101.35.247.235', 7709)]
        for host, port in servers:
            try:
                start_time = time.time()
                if api.connect(host, port):
                    response_time = (time.time() - start_time) * 1000
                    api.disconnect()
                    return {'connected': True, 'response_time': response_time, 'error': None}
            except:
                continue
        return {'connected': False, 'response_time': None, 'error': '所有服务器连接失败'}
    except ImportError:
        return {'connected': False, 'response_time': None, 'error': 'pytdx模块未安装'}
    except Exception as e:
        return {'connected': False, 'response_time': None, 'error': str(e)}

def check_akshare_connection():
    """检查akshare连接"""
    try:
        import akshare as ak
        start_time = time.time()
        df = ak.stock_zh_a_spot_em()
        response_time = (time.time() - start_time) * 1000
        if df is not None and not df.empty:
            return {'connected': True, 'response_time': response_time, 'error': None}
        return {'connected': False, 'response_time': None, 'error': '数据获取为空'}
    except ImportError:
        return {'connected': False, 'response_time': None, 'error': 'akshare模块未安装'}
    except Exception as e:
        return {'connected': False, 'response_time': None, 'error': str(e)}

def check_data_source_connectivity():
    """检查数据源连接状态 (V6 最终统一版)"""
    import requests
    
    sources = {
        '东方财富API': {'connected': False, 'response_time': None, 'error': None},
        'pytdx本地': {'connected': False, 'response_time': None, 'error': None},
        'akshare接口': {'connected': False, 'response_time': None, 'error': None}
    }

    # 1. 测试东方财富 (使用V5方案)
    try:
        session = requests.Session()
        session.trust_env = False
        url = "http://push2.eastmoney.com/api/qt/clist/get"
        params = {'pn': '1', 'pz': '1'} # 只请求1条数据用于测试
        start_time = time.time()
        response = session.get(url, params=params, timeout=10)
        response_time = (time.time() - start_time) * 1000
        if response.status_code == 200:
            sources['东方财富API']['connected'] = True
            sources['东方财富API']['response_time'] = response_time
        else:
            sources['东方财富API']['error'] = f"HTTP {response.status_code}"
    except Exception as e:
        sources['东方财富API']['error'] = str(e)

    # 2. 测试pytdx本地
    pytdx_status = check_pytdx_connection()
    if pytdx_status:
        sources['pytdx本地'] = pytdx_status

    # 3. 测试akshare (使用备用接口)
    try:
        import akshare as ak
        start_time = time.time()
        # 使用稳定的交易日接口测试
        trade_dates = ak.tool_trade_date_hist_sina()
        response_time = (time.time() - start_time) * 1000
        if len(trade_dates) > 0:
            sources['akshare接口']['connected'] = True
            sources['akshare接口']['response_time'] = response_time
        else:
            sources['akshare接口']['error'] = "返回数据为空"
    except Exception as e:
        sources['akshare接口']['error'] = str(e)

    # 3. 测试akshare
    akshare_status = check_akshare_connection()
    if akshare_status:
        sources['akshare接口'] = akshare_status

    return sources

def assess_module_health(MODULES_STATUS):
    """评估模块健康度"""
    module_names = {
        'cache_manager': '本地数据缓存管理器', 'stock_fetcher': '股票获取器',
        'pattern_analyzer': '形态分析模块', 'monitoring_system': '实时监控系统',
        'risk_manager': '数据源风险控制模块'
    }
    health_assessment = {}
    for key, name in module_names.items():
        module_class = MODULES_STATUS.get(key)
        health_info = {'name': name, 'health_score': 0, 'details': [], 'suggestions': []}
        if module_class is None:
            health_info['details'].append("模块未加载")
            health_info['suggestions'].append("检查模块文件是否存在或依赖是否安装")
        else:
            health_info['health_score'] = 60
            health_info['details'].append("模块已加载")
            try:
                instance = module_class()
                health_info['health_score'] += 20
                health_info['details'].append("模块可实例化")
                # Add specific checks for each module here if needed
            except Exception as e:
                health_info['suggestions'].append(f"模块实例化失败: {str(e)[:50]}")
        health_assessment[key] = health_info
    return health_assessment

def generate_diagnosis_suggestions(overall_health, module_health, data_source_status, performance_metrics):
    """生成智能诊断建议"""
    suggestions = []
    if overall_health < 50:
        suggestions.append("🚨 系统健康度严重偏低，建议立即检查和修复关键模块")
    elif overall_health < 70:
        suggestions.append("⚠️ 系统健康度偏低，建议优化模块配置和数据源连接")
    
    disconnected_sources = [name for name, info in data_source_status.items() if not info['connected']]
    if disconnected_sources:
        suggestions.append(f"🌐 数据源连接异常: {', '.join(disconnected_sources)}，检查网络和配置")
        
    if performance_metrics['cpu_percent'] > 80:
        suggestions.append("⚡ CPU使用率过高，建议关闭不必要的程序或优化算法")
    return suggestions

def generate_optimization_suggestions(performance_metrics, module_health):
    """生成系统优���建议"""
    suggestions = []
    if performance_metrics['cpu_percent'] > 50:
        suggestions.append("考虑启用多线程处理以提高CPU利用效率")
    suggestions.append("定期更新股票数据以保持分析准确性")
    return suggestions

def professional_system_diagnosis(MODULES_STATUS):
    """专业系统诊断"""
    print("\n" + "="*80)
    print("🏥 户部尚赢量化分析系统 - 专业诊断报告")
    print("="*80)
    print(f"📅 诊断时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

    performance_metrics = get_system_performance()
    print(f"\n⚡ 系统性能指标:")
    print(f"  - CPU使用率: {performance_metrics['cpu_percent']:.1f}%")
    print(f"  - 内存使用: {performance_metrics['memory_used']:.1f}MB / {performance_metrics['memory_total']:.1f}MB ({performance_metrics['memory_percent']:.1f}%)")

    module_health = assess_module_health(MODULES_STATUS)
    print(f"\n🔧 核心模块健康度评估:")
    total_health = sum(info['health_score'] for info in module_health.values())
    module_count = len(module_health)
    overall_health = total_health / module_count if module_count > 0 else 0
    for module_info in module_health.values():
        print(f"  {get_health_status_icon(module_info['health_score'])} {module_info['name']}: {module_info['health_score']}/100分")

    print(f"\n🏥 系统整体健康度: {overall_health:.1f}/100分 {get_health_status_icon(overall_health)}")

    data_source_status = check_data_source_connectivity()
    print(f"\n🌐 数据源连接状态:")
    for source_name, source_info in data_source_status.items():
        status_icon = "🟢" if source_info['connected'] else "🔴"
        print(f"  {status_icon} {source_name}: {'连接正常' if source_info['connected'] else '连接失败'}")

    diagnosis_suggestions = generate_diagnosis_suggestions(overall_health, module_health, data_source_status, performance_metrics)
    if diagnosis_suggestions:
        print(f"\n🔍 智能诊断建议:")
        for i, suggestion in enumerate(diagnosis_suggestions, 1):
            print(f"  {i}. {suggestion}")
            
    print("="*80)
    return overall_health >= 70
